#include "../thread_pool/thread_pool.h"

#include "basic/basic.h"
#include "utils/system.h"

namespace eyas {
namespace thread {
//
// ThreadPool
//
thread_pool::thread_pool()
	:capacity_(0), ioservice_myself_(true)
	, service_(new boost::asio::io_service(eyas::system::get_cpu_core_count()))
	, work_(new boost::asio::io_service::work(*service_)){
	unsigned int capacity = 0;
	if(0 == capacity_){
		// 默认为cpu核心数的2倍
		capacity = eyas::system::get_cpu_core_count();
	}
	this->capacity(capacity);

}
thread_pool::thread_pool(unsigned int capacity)
	:capacity_(0), ioservice_myself_(true)
	, service_(new boost::asio::io_service(eyas::system::get_cpu_core_count()))
	, work_(new boost::asio::io_service::work(*service_)){
	this->capacity(capacity);
}
thread_pool::thread_pool(boost::asio::io_service& service)
	:capacity_(0), ioservice_myself_(false)
	, service_(&service)
	, work_(new boost::asio::io_service::work(service)){
	unsigned int capacity = 0;
	if(0 == capacity_){
		// 默认为cpu核心数的2倍
		capacity = eyas::system::get_cpu_core_count()*2;
	}
	this->capacity(capacity);
}
thread_pool::thread_pool(boost::asio::io_service& service, unsigned int capacity)
	:capacity_(0), ioservice_myself_(false)
	, service_(&service)
	, work_(new boost::asio::io_service::work(service)){
	this->capacity(capacity);
}
thread_pool::~thread_pool() {
	for(thread_map::iterator it = this->thread_map_.begin(); it != this->thread_map_.end(); it++){
		it->second->set_enable(false);
	}
	if(nullptr != work_){
		delete work_;
		work_ = nullptr;
	}
	this->thread_map_.clear();
	if(this->ioservice_myself_){
		delete this->service_;
	}
	this->service_ = nullptr;
}
void thread_pool::capacity(unsigned int capacity){
	// 调整线程池线程个数
	for(unsigned int i=this->capacity_; i<capacity; i++){
		// 增加线程
		thread_pool_worker_ptr worker_ptr = thread_pool_worker_ptr(new thread_pool_worker(this));
		this->thread_map_[worker_ptr->get_thread_id()] = worker_ptr;
	}
	this->capacity_ = this->thread_map_.size();
}
void thread_pool::work(thread_pool_worker* worker){
	this->service_->run();
}

}
}
